﻿using System.Collections.Generic;
using System.Linq;
using RimWorld;
using UnityEngine;
using Verse;

namespace RimZombieGirl
{
    public class GameComponent_CurseManager : GameComponent
    {
        // key: map unique ID, value: 累计诅咒值
        public Dictionary<int, float> cachedMapCurses = new Dictionary<int, float>();

        public GameComponent_CurseManager(Game game) : base()
        {
        }

        public override void GameComponentTick()
        {
            base.GameComponentTick();

            // 每 2500 tick（约1小时）检查一次
            if (Find.TickManager.TicksGame % 2500 != 0) return;

            // 检查所有已加载地图
            foreach (Map map in Find.Maps)
            {
                var comp = map.GetComponent<MapComponent_Curse>();
                if (comp != null && comp.currentCurseValue > 0f)
                {
                    // 如果已经有缓存，更新，否则添加
                    cachedMapCurses[map.uniqueID] = comp.targetCurseValue;
                }
            }
        }

        /// <summary>
        /// 当地图被卸载时，保存其残留诅咒值
        /// </summary>
        public void CacheMapCurse(Map map)
        {
            var comp = map.GetComponent<MapComponent_Curse>();
            if (comp != null && comp.currentCurseValue > 0f)
            {
                cachedMapCurses[map.uniqueID] = comp.targetCurseValue;
            }
        }

        /// <summary>
        /// 触发“诅咒复苏”，把所有累计诅咒值加到当前地图
        /// </summary>
        public void ResurrectCursesToMap(Map targetMap)
        {
            if (cachedMapCurses.Count == 0) return;

            var comp = targetMap.GetComponent<MapComponent_Curse>();
            if (comp == null) return;

            float totalCurse = cachedMapCurses.Values.Sum();
            comp.AddTargetCurseValue(totalCurse);            

            // 清空缓存
            cachedMapCurses.Clear();
        }

        public override void ExposeData()
        {
            base.ExposeData();
            Scribe_Collections.Look(ref cachedMapCurses, "cachedMapCurses", LookMode.Value, LookMode.Value);
            if (cachedMapCurses == null)
                cachedMapCurses = new Dictionary<int, float>();
        }
    }
}
